package cn.gzjp.modules.logis.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.logis.entity.LogisMessage;
import cn.gzjp.modules.logis.service.LogisMessageService;

/**
 * 消息Controller
 * @author zengcp
 * @version 2018-05-16
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisMessage")
public class LogisMessageController extends BaseController {

	@Autowired
	private LogisMessageService logisMessageService;
	
	
	/**
	 * 消息列表页面
	 */
	@RequiresPermissions("logis:logisMessage:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisMessage logisMessage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisMessage> page = logisMessageService.findPage(new Page<LogisMessage>(request, response), logisMessage); 
		model.addAttribute("page", page);
		return "modules/logis/logisMessageList";
	}

	/**
	 * 查看，增加，编辑消息表单页面
	 */
	@RequiresPermissions(value={"logis:logisMessage:view","logis:logisMessage:add","logis:logisMessage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisMessage logisMessage, Model model) {
		model.addAttribute("logisMessage", logisMessage);
		return "modules/logis/logisMessageForm";
	}

	/**
	 * 保存消息
	 */
	@RequiresPermissions(value={"logis:logisMessage:add","logis:logisMessage:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisMessage logisMessage, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisMessage)){
			return form(logisMessage, model);
		}
		if(!logisMessage.getIsNewRecord()){//编辑表单保存
			LogisMessage t = logisMessageService.get(logisMessage.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisMessage, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			logisMessageService.save(t);//保存
		}else{//新增表单保存
			logisMessageService.save(logisMessage);//保存
		}
		addMessage(redirectAttributes, "保存消息成功");
		return redirect("/logis/logisMessage/?repage");
	}
	
	/**
	 * 删除消息
	 */
	@RequiresPermissions("logis:logisMessage:del")
	@RequestMapping(value = "delete")
	public String delete(LogisMessage logisMessage, RedirectAttributes redirectAttributes) {
		logisMessageService.delete(logisMessage);
		addMessage(redirectAttributes, "删除消息成功");
		return redirect("/logis/logisMessage/?repage");
	}
	
	/**
	 * 批量删除消息
	 */
	@RequiresPermissions("logis:logisMessage:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisMessageService.delete(logisMessageService.get(id));
		}
		addMessage(redirectAttributes, "删除消息成功");
		return redirect("/logis/logisMessage/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisMessage:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisMessage logisMessage, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "消息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisMessage> page = logisMessageService.findPage(new Page<LogisMessage>(request, response, -1), logisMessage);
    		new ExportExcel("消息", LogisMessage.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出消息记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisMessage/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisMessage:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisMessage> list = ei.getDataList(LogisMessage.class);
			for (LogisMessage logisMessage : list){
				try{
					logisMessageService.save(logisMessage);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条消息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条消息记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入消息失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisMessage/?repage");
    }
	
	/**
	 * 下载导入消息数据模板
	 */
	@RequiresPermissions("logis:logisMessage:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "消息数据导入模板.xlsx";
    		List<LogisMessage> list = Lists.newArrayList(); 
    		new ExportExcel("消息数据", LogisMessage.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisMessage/?repage");
    }
	@ModelAttribute
	public LogisMessage get(@RequestParam(required=false) String id) {
		LogisMessage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisMessageService.get(id);
		}
		if (entity == null){
			entity = new LogisMessage();
		}
		return entity;
	}
	

}